package com.agilegroup.crm.utils;

import static com.agilegroup.crm.utils.CONSTANTS.CONTACT_COMPANY;
import static com.agilegroup.crm.utils.CONSTANTS.CONTACT_DISPLAY_NAME;
import static com.agilegroup.crm.utils.CONSTANTS.CONTACT_MOBILE_NUMBER;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

import com.agilegroup.crm.database.ContactDAO;
import com.agilegroup.crm.model.ContactData;
import com.agilegroup.crm.model.ContactStatus;

public class ContactsSync {

	private List<ContactData>contactData;
	private ContactDAO contactDAO;
	public ContactsSync(List<ContactData>contactData) {
		this.contactData = contactData;
	}
	public ArrayList<HashMap<String, String>> getContacts(){
		ArrayList<HashMap<String, String>> contactDataList = new ArrayList<HashMap<String, String>>();
		
		for (ContactData contact : contactData) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("contact_id", contact.getId().toString());
			map.put(CONTACT_DISPLAY_NAME, contact.getfName());
			map.put(CONTACT_COMPANY, contact.getAccountName());
			//map.put(CONTACT_EMAIL, contact.get);
			map.put(CONTACT_MOBILE_NUMBER, contact.getMobile());
			//map.put(CONTACT_WORK_NUMBER, contact.getPhone());
			contactDataList.add(map);
		}
		return contactDataList;
	}
	
	public void createContacts(Activity activity) {
		
		HashMap<String, String> data = new HashMap<String, String>();
		ArrayList < ContentProviderOperation > contactGroup = new ArrayList < ContentProviderOperation > ();
		
     	contactDAO = new ContactDAO(activity);
     	
     	List<ContactStatus>contactStatus  = contactDAO.getContacts();
		Long myContactsGroupId = null;
		    try {
		    	String groupCkecher = ContactsContract.Groups.TITLE + " = 'Asset Security Group'  AND  " + ContactsContract.Groups.GROUP_VISIBLE + " = 1";
		    	Cursor cursorGroup = activity.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, new String[] {"_id"}, groupCkecher, null, "_id");
			    if (cursorGroup.moveToFirst()) {
			        myContactsGroupId = cursorGroup.getLong(0);
			    }
			    if(myContactsGroupId==null){
		        	contactGroup.add(ContentProviderOperation.newInsert(
			    			 ContactsContract.Groups.CONTENT_URI)
			    			     .withValue(ContactsContract.Groups.TITLE, "Asset Security Group")
			    			     .withValue(ContactsContract.Groups.GROUP_VISIBLE, 1)
			    			     .build());
			    	activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, contactGroup);
		        }
		    	String sqlWhere = ContactsContract.Groups.TITLE + " = 'Asset Security Group'  AND  " + ContactsContract.Groups.GROUP_VISIBLE + " = 1";
			    Cursor cursor = activity.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, new String[] {"_id"}, sqlWhere, null, "_id");
			    if (cursor.moveToFirst()) {
			        myContactsGroupId = cursor.getLong(0);
			    }
				
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (OperationApplicationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		for (int i = 0; i < getContacts().size(); i++) {
			data=getContacts().get(i);
			String contact_id = data.get("contact_id");
			String DisplayName = data.get(CONTACT_DISPLAY_NAME);
			String MobileNumber = data.get(CONTACT_MOBILE_NUMBER);
			//String WorkNumber = data.get(CONTACT_WORK_NUMBER);
			//String Email = data.get(CONTACT_EMAIL);
			String Company = data.get(CONTACT_COMPANY);
			
			if(contactStatus.size()>0){
				boolean isSynced = contactDAO.checkContactIsSynced(contact_id);
				if(isSynced==true){
					Log.d(ContactsSync.class.getSimpleName(), "Already synced");
				}
				else{
					ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();
					int rawContactInsertIndex = ops.size();

					 ops.add(ContentProviderOperation.newInsert(
					 ContactsContract.RawContacts.CONTENT_URI)
					     .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
					     .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
					     .build());

					 ///add group to contact
					 ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
				                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
				                .withValue(ContactsContract.Data.MIMETYPE,
				                        ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
				                .withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, myContactsGroupId)
				                .build());
					 
					 //------------------------------------------------------ Names
					 if (DisplayName != null&&!DisplayName.equals("")) {
					     ops.add(ContentProviderOperation.newInsert(
					     ContactsContract.Data.CONTENT_URI)
					         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
					         .withValue(ContactsContract.Data.MIMETYPE,
					     ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
					         .withValue(
					     ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
					     DisplayName).build());
					 }

					 //------------------------------------------------------ Mobile Number                     
					 if (MobileNumber != null&&!MobileNumber.equals("")) {
					     ops.add(ContentProviderOperation.
					     newInsert(ContactsContract.Data.CONTENT_URI)
					         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
					         .withValue(ContactsContract.Data.MIMETYPE,
					     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
					         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
					         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
					     ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
					         .build());
					 }

					 //------------------------------------------------------ Work Numbers
//					 if (WorkNumber != null&&!WorkNumber.equals("")) {
//					     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
//					         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
//					         .withValue(ContactsContract.Data.MIMETYPE,
//					     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
//					         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
//					         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
//					     ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
//					         .build());
//					 }

					 //------------------------------------------------------ Email
//					 if (Email != null&&!Email.equals("")) {
//					     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
//					         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
//					         .withValue(ContactsContract.Data.MIMETYPE,
//					     ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
//					         .withValue(ContactsContract.CommonDataKinds.Email.DATA, Email)
//					         .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
//					         .build());
//					 }

					 //------------------------------------------------------ Organization
					 if(Company!=null){
						 ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
						         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
						         .withValue(ContactsContract.Data.MIMETYPE,
						     ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
						         .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, Company)
						         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
						         //.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
						         //.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
						         .build());
					 	}
					 
					 try {
						 activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
						 contactDAO.createContact(contact_id, "true");
					 } catch (Exception e) {
					     e.printStackTrace();
					     Toast.makeText(activity.getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
					 } 
				}
				
			}
			else{
				ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();
				int rawContactInsertIndex = ops.size();

				 ops.add(ContentProviderOperation.newInsert(
				 ContactsContract.RawContacts.CONTENT_URI)
				     .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
				     .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
				     .build());

				 ///add group to contact
				 ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
			                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
			                .withValue(ContactsContract.Data.MIMETYPE,
			                        ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
			                .withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, myContactsGroupId)
			                .build());
				 
				 //------------------------------------------------------ Names
				 if (DisplayName != null&&!DisplayName.equals("")) {
				     ops.add(ContentProviderOperation.newInsert(
				     ContactsContract.Data.CONTENT_URI)
				         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
				         .withValue(ContactsContract.Data.MIMETYPE,
				     ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
				         .withValue(
				     ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
				     DisplayName).build());
				 }

				 //------------------------------------------------------ Mobile Number                     
				 if (MobileNumber != null&&!MobileNumber.equals("")) {
				     ops.add(ContentProviderOperation.
				     newInsert(ContactsContract.Data.CONTENT_URI)
				         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
				         .withValue(ContactsContract.Data.MIMETYPE,
				     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
				         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
				         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
				     ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
				         .build());
				 }

				 //------------------------------------------------------ Work Numbers
//				 if (WorkNumber != null&&!WorkNumber.equals("")) {
//				     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
//				         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
//				         .withValue(ContactsContract.Data.MIMETYPE,
//				     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
//				         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
//				         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
//				     ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
//				         .build());
//				 }

				 //------------------------------------------------------ Email
//				 if (Email != null&&!Email.equals("")) {
//				     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
//				         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
//				         .withValue(ContactsContract.Data.MIMETYPE,
//				     ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
//				         .withValue(ContactsContract.CommonDataKinds.Email.DATA, Email)
//				         .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
//				         .build());
//				 }

				 //------------------------------------------------------ Organization
				 if(Company!=null){
					 ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
					         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
					         .withValue(ContactsContract.Data.MIMETYPE,
					     ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
					         .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, Company)
					         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
					         //.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
					         //.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
					         .build());
				 	}
				 
				 try {
					 activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
					 contactDAO.createContact(contact_id, "true");
				 } catch (Exception e) {
				     e.printStackTrace();
				     Toast.makeText(activity.getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
				 } 
			}
		}
		contactDAO.close();
		Toast.makeText(activity.getApplicationContext(), "The Contacts Have successfully synced to the phone", Toast.LENGTH_SHORT).show();
   }
}
